package http_proxy

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type HttpProxy struct {
	ip   string
	port int
}

func (p *HttpProxy) Handle(targetUrl string) ([]byte, error) {
	_url := fmt.Sprintf("http://%s:%d", p.ip, p.port)
	origin, err := url.Parse(_url)
	if err != nil {
		return nil, err
	}
	netTransport := &http.Transport{
		Proxy: http.ProxyURL(origin),
	}
	client := &http.Client{
		Timeout:   time.Second * 20, //设置连接超时时间
		Transport: netTransport,
	}
	return proxy(client, targetUrl)
}

func proxy(client *http.Client, url string) ([]byte, error) {
	res, err := client.Get(url)
	defer res.Body.Close()

	if err != nil {
		return nil, err
	}

	body, err := ioutil.ReadAll(res.Body)
	return body, err
}
